/**
 * 经典书籍导入器
 * 提供批量导入和管理经典书籍的功能
 */

import { addClassicBooksToBookshelf, hasClassicBooks, getClassicBooksList } from './add-classic-books';

export interface ImportResult {
  success: boolean;
  addedCount: number;
  skippedCount: number;
  totalCount: number;
  message: string;
}

/**
 * 批量导入经典书籍
 */
export async function importClassicBooks(): Promise<ImportResult> {
  try {
    const books = getClassicBooksList();
    const totalCount = books.length;
    
    // 检查是否已有经典书籍
    const hasExisting = await hasClassicBooks();
    
    if (hasExisting) {
      return {
        success: true,
        addedCount: 0,
        skippedCount: totalCount,
        totalCount,
        message: '经典书籍已存在，跳过导入',
      };
    }
    
    // 执行导入
    await addClassicBooksToBookshelf();
    
    return {
      success: true,
      addedCount: totalCount,
      skippedCount: 0,
      totalCount,
      message: `成功导入 ${totalCount} 本经典书籍`,
    };
    
  } catch (error) {
    console.error('导入经典书籍失败:', error);
    
    return {
      success: false,
      addedCount: 0,
      skippedCount: 0,
      totalCount: 0,
      message: `导入失败: ${(error as Error).message}`,
    };
  }
}

/**
 * 获取导入状态
 */
export async function getImportStatus(): Promise<{
  hasClassicBooks: boolean;
  totalBooks: number;
}> {
  const hasExisting = await hasClassicBooks();
  const books = getClassicBooksList();
  
  return {
    hasClassicBooks: hasExisting,
    totalBooks: books.length,
  };
}

/**
 * 预览经典书籍列表
 */
export function previewClassicBooks() {
  return getClassicBooksList().map(book => ({
    title: book.bookname,
    author: book.author,
    chapters: book.chapterCount,
    description: book.intro.substring(0, 100) + '...',
  }));
}